﻿using Microsoft.Win32;

namespace Update
{
    public class RegistryHelper
    {
        static RegistryKey root = Registry.LocalMachine;
        static RegistryKey softKey = root.OpenSubKey("SOFTWARE", true);

        public RegistryHelper() { }

        /// <summary>
        /// 读取指定名称的注册表的值
        /// </summary>
        /// <param name="subkey"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetRegistryData(string name)
        {
            string registData = "";
            //RegistryKey myKey = root.OpenSubKey(subkey, true);
            //RegistryKey myKey = root.OpenSubKey(subkey, RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
            
            RegistryKey myKey = softKey.OpenSubKey("SFJDManagement", true);
            if (myKey != null)
            {
                registData = myKey.GetValue(name).ToString();
            }
            return registData;
        }

        /// <summary>
        /// 向注册表中写数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tovalue"></param> 
        public void SetRegistryData(string name, string value)
        {
            softKey.SetValue(name, value);
        }

        /// <summary>
        /// 删除注册表中指定的注册表项
        /// </summary>
        /// <param name="name"></param>
        public void DeleteRegist(string name)
        {
            string[] subkeyNames;
            subkeyNames = softKey.GetSubKeyNames();
            foreach (string aimKey in subkeyNames)
            {
                if (aimKey == name)
                    softKey.DeleteSubKeyTree(name);
            }
        }

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsRegistryExist(string name)
        {
            bool _exit = false;
            string[] subkeyNames;
            subkeyNames = softKey.GetSubKeyNames();
            foreach (string keyName in subkeyNames)
            {
                if (keyName == name)
                {
                    _exit = true;
                    return _exit;
                }
            }
            return _exit;
        }
    }
}
